package com.heima.juc.n4.deadlock.v1;

import com.heima.juc.n2.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * @author : leimingchao
 * @date Date : 2022年02月11日 21:05
 */
@Slf4j(topic = "c.TestDeadLock2")
public class TestDeadLock2 {

    public static void main(String[] args) {
        Chopstick2 chopstick1 = new Chopstick2("1");
        Chopstick2 chopstick2 = new Chopstick2("2");
        Chopstick2 chopstick3 = new Chopstick2("3");
        Chopstick2 chopstick4 = new Chopstick2("4");
        Chopstick2 chopstick5 = new Chopstick2("5");

        new Philosopher2("苏格拉底", chopstick1, chopstick2).start();
        new Philosopher2("柏拉图", chopstick2, chopstick3).start();
        new Philosopher2("亚里士多德", chopstick3, chopstick4).start();
        new Philosopher2("赫拉克利特", chopstick4, chopstick5).start();
        new Philosopher2("阿基米德", chopstick1, chopstick5).start();
    }
}

@Slf4j(topic = "c.Philosopher2")
class Philosopher2 extends Thread {

     Chopstick2 left;
     Chopstick2 right;

    public Philosopher2(String name, Chopstick2 left, Chopstick2 right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {

            //尝试获得左手筷子
            synchronized (left) {

                //尝试获得右手筷子
                synchronized (right) {
                    eat();
                }
            }
        }
    }

    Random random = new Random();

    private void eat() {
        log.debug("eating....");
        Sleeper.sleep(0.5);
    }
}

class Chopstick2 {

    String name;

    public Chopstick2(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "筷子 {" + name + "}";
    }
}
